<template>
  <div>
    <el-dialog v-model="selectDialogVisible" title="组织结构" width="700">
      <div class="main">
        <div class="left">
          <div class="headerP">
            <p
              class="headerText"
              @click="goUp(item.id, index)"
              v-for="(item, index) in headerTree"
            >
              {{ item.deptName }} >
            </p>
          </div>
          <ul class="select-box">
            <template v-if="departments.length">
              <li class="content" v-for="item in showList" :key="item.deptId">
                <el-checkbox
                  class="checkbox"
                  v-model="item.selected"
                  @change="changeEvent(item)"
                >
                  <div style="display: flex; flex-direction: row">
                    <div class="f11">
                      <el-icon style="font-size: 20px">
                        <Share />
                      </el-icon>
                    </div>
                    <div v-if="!userShow" class="f12">
                      {{ item.deptName }}
                    </div>
                    <div v-if="userShow" class="f12">{{ item.nickName }}</div>
                  </div>
                </el-checkbox>
                <div
                  class="d22"
                  v-if="item.child || item.userVoList"
                  @click="queryData(item)"
                >
                  下级
                </div>
              </li>
            </template>
          </ul>
        </div>
        <div class="right">
          <div v-for="item in checkList" class="rightDiv">
            {{ item.name }}
            <el-icon @click="delCheck(item.id)" class="rightDivIcon"
              ><Close
            /></el-icon>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="selectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sureCheck"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <template v-if="showStyle === 1">
      <el-button
        :type="disabled ? 'info' : 'primary'"
        :disabled="disabled"
        :icon="$icon['Plus']"
        circle
        size="large"
        @click="openTree"
      >
      </el-button>
      <div style="width: 100%; margin-top: 10px; text-align: left">
        <!-- <org-item v-model:data="defaultValue"  :disabled="disabled"/> -->
      </div>
    </template>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import { orgTree, orgTreeSearcheUser } from "../../api/dept/index";
import {
  Delete,
  Edit,
  Search,
  Share,
  Guide,
  Grid,
} from "@element-plus/icons-vue";
import { id } from "element-plus/es/locales.mjs";
const emit = defineEmits(["get-range-list", "get-admin-list"]);
let props = defineProps({
  // 这里是父组件给的值
  disableSelectChildrenDept: {
    //禁止选择下级部门
    type: Boolean,
    default: true,
  },
  // 这个是数据类型 为数组
  orgList: {
    type: Array,
    default: () => [],
  },
  // 禁止选择人的开关
  disableUser: {
    type: Array,
    default: () => [],
  },
  // 类型
  type: {
    type: String,
    default: "org",
  },
  // 是否可以多选
  multiple: {
    type: Boolean,
    default: true,
  },
  // 禁止选择
  disabled: {
    type: Boolean,
    default: false,
  },
  // 控制 展示的样式
  showStyle: {
    type: Number,
    default: 1,
  },
  // 默认值
  placeholder: {
    type: String,
    default: "请选择",
  },
  // 是否展示那个tag
  showTag: {
    type: Boolean,
    default: true,
  },
  // 是否默认展示为单选全员
  radioAll: {
    type: String,
    default: "true",
  },
  // 选择的人员类型
  selectType: {
    type: String,
    default: "range",
  },
});
let selectDialogVisible = ref(false);
const headerTree = ref([{ id: 0, deptName: "根节点" }]);
let departments = ref([]);
let showList = ref([]);
let pid = ref();
const checkList = ref([]);
//     let showList = computed(() => {
//         if (departments.value.child) {
//             return departments.value.child;
//         }
// 	    return []
// })
const changeEvent = (val) => {
  if (userShow.value) {
    // checkList.value.push({
    //   id: val.userId,
    //   name: val.nickName,
    //   type: "dept",
    // });
    let indexToRemove = checkList.value.findIndex(
      (item) => item.id === val.userId
    );

    if (indexToRemove !== -1) {
      // 如果存在相同 value 的对象，则从数组中删除
      checkList.value.splice(indexToRemove, 1);
    } else {
      // 如果不存在相同 value 的对象，则添加到数组
      checkList.value.push({
        id: val.userId,
        name: val.nickName,
        type: "dept",
      });
    }
  } else {
    // checkList.value.push({
    //   id: val.deptId,
    //   name: val.deptName,
    //   type: "user",
    // });
    let indexToRemove = checkList.value.findIndex(
      (item) => item.id === val.deptId
    );

    if (indexToRemove !== -1) {
      // 如果存在相同 value 的对象，则从数组中删除
      checkList.value.splice(indexToRemove, 1);
    } else {
      // 如果不存在相同 value 的对象，则添加到数组
      checkList.value.push({
        id: val.deptId,
        name: val.deptName,
        type: "user",
      });
    }
  }
};

const sureChecks = (val) => {
  for (let obj1 of val) {
    // 遍历第二个数组中的每个对象
    for (let obj2 of checkList.value) {
      // 如果两个对象的 ID 相同，则返回 true
      if (obj1.deptId === obj2.id) {
        return true;
      }
    }
  }
  // 如果没有找到相同的 ID，则返回 false
  return false;
};

const delCheck = (val) => {
  checkList.value = checkList.value.filter((item) => item.id != val);
};
const getDepartmentList = async (parentId = 0, type = "org") => {
  // let { data } = await getDepartments({ parentId })

  let { data } = await orgTree(type, parentId);
  departments.value = data;
  headerTree.value = [{ id: 0, deptName: "根节点" }];
  showList.value = [];
  headerTree.value.push({
    id: departments.value[0].parentId,
    deptName: departments.value[0].deptName,
  });
  showList.value = departments.value[0].child;
};
const openTree = () => {
  getDepartmentList();
  selectDialogVisible.value = true;
};
let userShow = ref(false);
// 下一级
const queryData = (val) => {
  if (val.child) {
    userShow.value = false;
    pid.value = val.deptId;
    headerTree.value.push({ id: val.parentId, deptName: val.deptName });
    showList.value = val.child;
  } else if (val.userVoList) {
    userShow.value = true;
    pid.value = val.deptId;
    headerTree.value.push({ id: val.parentId, deptName: val.deptName });
    showList.value = val.userVoList;
  } else {
    userShow.value = true;
    showList.value = val.userVoList;
  }
};
//    返回上一级
const goUp = async (val, indexs) => {
  // showList.value= departments.value.filter((item) =>{
  //     return  findTree(item,val)
  // } )
  userShow.value = false;
  findTree(departments.value, val);

  if (indexs > 0) {
    headerTree.value = headerTree.value.slice(0, indexs + 1);
  } else {
    headerTree.value = headerTree.value.slice(0, 2);
  }
};
//    递归树形结构
const findTree = (items, val) => {
  // 递归查找匹配 val 的部门
  for (const item of items) {
    if (item.parentId == val) {
      showList.value = item.child;
      return showList.value ? findTree(item.child, val) : null;
    }
  }
};
/**
 * 确定
 */
const sureCheck = () => {
  props.selectType === "range"
    ? emit("get-range-list", checkList.value)
    : emit("get-admin-list", checkList.value);

  selectDialogVisible.value = false;
};
</script>
<style scoped>
.main {
  width: 100%;
  min-height: 500px;
  display: flex;
}
.left {
  width: 50%;
  height: 100%;
  padding: 10px 10px;
  overflow-y: auto;
  border-right: 1px solid #000;
  min-height: 500px;
}
.right {
  width: 50%;
  height: 100%;
  padding: 10px 10px;
  /* border-left: 1px solid #000;
  min-height: 500px; */
  display: flex;
  flex-wrap: wrap;
}
.rightDiv {
  font-size: 14px;
  height: 30px;
  margin-right: 8px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  padding-right: 20px;
  line-height: 30px;
  padding-left: 8px;
  position: relative;
}
.rightDivIcon {
  position: absolute;
  top: 5px;
  right: 0;
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.content {
  width: 100%;
  display: flex;
  height: 35px;
  align-items: center;
  position: relative;
}
.checkbox {
  width: 70%;
  height: 100%;
}
.d22 {
  width: 30%;
  height: 100%;
  position: absolute;
  top: 0;
  right: 0;
  cursor: pointer;
  font-size: 14px;
  color: blue;
}
.headerP {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.headerText {
  margin-right: 8px;
  cursor: pointer;
}
</style>
